package com.kfm.servlet;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.kfm.map.ServerTA;
import com.kfm.tool.ServerFile;
import com.kfm.tool.ServerServlet;
import lombok.SneakyThrows;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.Map;
import java.util.Set;

@WebServlet("/selectServer")
public class SelectServer extends HttpServlet {
    @SneakyThrows
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        PrintWriter writer = response.getWriter();
        JSONArray array = JSONUtil.createArray();
        List<ServerTA> result = ServerServlet.getResult();
        for (ServerTA serverTA : result) {
            int resp = ServerServlet.getResponse(serverTA.getUrl());
            if (resp == 200) {
                boolean ftp = ServerServlet.ftp(serverTA);
                String json = "{" + "\"URL\":" + "\"" + serverTA.getUrl()  + "\""+ "," + "\"message\":"  + "\""+ resp  + "\""+ ","
                        + "\"upload\":"  + "\""+ ftp + "\""+ ","+ "\"admin\":"+ "\"" + serverTA.getAdministrator() + "\""+ ","+
                        "\"email\":" + "\""+ serverTA.getEmail()+ "\"" + "}";
                System.out.println(json);
                array.add(json);
            } else {
                String json = "{" + "\"URL\":" + "\"" + serverTA.getUrl()  + "\""+ "," + "\"message\":"  + "\""+ resp  + "\""+ ","
                        + "\"upload\":"  + "\""+ false + "\""+ ","+ "\"admin\":"+ "\"" + serverTA.getAdministrator() + "\""+ ","+
                        "\"email\":" + "\""+ serverTA.getEmail()+ "\"" + "}";
                array.add(json);
            }
        }
        String jsonStr = JSONUtil.toJsonStr(array);
        writer.write(jsonStr);
        writer.close();
    }
}
